package com.platform.controller.shop;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.platform.config.RemoteConfig;
import com.platform.dao.shop.UserRecordDao;
import com.platform.entity.MlsUserEntity2;
import com.platform.entity.shop.*;
import com.platform.service.shop.*;
import com.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.platform.entity.SysUserEntity;
import org.springframework.web.client.RestTemplate;


/**
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-13 10:41:09
 */
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
	@Autowired
	private OrderGoodsService orderGoodsService;
	@Autowired
    ShippingService shippingService;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private RemoteConfig remoteConfig;

    @Autowired
    private MlsUserService mlsUserService;
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private UserRecordDao userRecordDao;

    @Autowired
    private UserService userService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("order:list")
    public R list(@RequestParam Map<String, Object> params) {
        SysUserEntity sysUserEntity= ShiroUtils.getUserEntity();
        // 查询列表数据
        Query query = new Query(params);
        query.put("merchantId",sysUserEntity.getMerchantId());
        List<OrderEntity> orderList = orderService.queryList(query);
        int total = orderService.queryTotal(query);
        for(OrderEntity user : orderList) {
        	user.setUserName(Base64.decode(user.getUserName()));
        }
        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 列表
     */
    @RequestMapping("/groupList")
    public R groupList(@RequestParam Map<String, Object> params) {
        SysUserEntity sysUserEntity= ShiroUtils.getUserEntity();
        // 查询列表数据
        Query query = new Query(params);
        query.put("merchantId",sysUserEntity.getMerchantId());
        List<GroupBuyingEntity> list = orderService.queryGroupList(query);
        int total = orderService.queryGroupTotal(query);
        PageUtils pageUtil = new PageUtils(list, total, query.getLimit(), query.getPage());
        return R.ok().put("templates/page", pageUtil);
    }



    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("order:info")
    public R info(@PathVariable("id") Integer id) {
        OrderEntity order = orderService.queryObject(id);
        Map<String, Object> params =new HashMap<String, Object>();
        params.put("orderId", order.getId());
        List<OrderGoodsEntity> list=  orderGoodsService.queryList(params);
        String goodsName="";
        //商品规格详情
      	String goodsSpecifitionNameValue="";
        for (OrderGoodsEntity orderGoodsEntity : list) {
        	goodsName=goodsName+orderGoodsEntity.getGoodsName()+"："+orderGoodsEntity.getNumber()+"（盒）："+orderGoodsEntity.getRetailPrice()+"（权益价），";
			if(orderGoodsEntity.getGoodsSpecifitionNameValue()!=null) {
				goodsSpecifitionNameValue=goodsSpecifitionNameValue+orderGoodsEntity.getGoodsSpecifitionNameValue()+",";
			}
		}
        order.setGoodsNames(goodsName);
        order.setGoodsSpecifitionNameValue(goodsSpecifitionNameValue);
        order.setUserName(Base64.decode(order.getUserName()));
        order.setAddress(order.getProvince() + order.getCity() + order.getDistrict() + order.getAddress());
        return R.ok().put("order", order);
    }

    /**
     * 信息
     */
    @RequestMapping("/goodsinfo/{gid}")
    @RequiresPermissions("order:info")
    public R goodsinfo(@PathVariable("gid") Integer gid) {
    	OrderGoodsEntity orderGoods = orderGoodsService.queryObject(gid);
        return R.ok().put("orderGoods", orderGoods);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("order:save")
    public R save(@RequestBody OrderEntity order) {
        orderService.save(order);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("order:update")
    public R update(@RequestBody OrderEntity order) {
        orderService.update(order);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("order:delete")
    public R delete(@RequestBody Integer[] ids) {
        orderService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<OrderEntity> list = orderService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public R queryTotal(@RequestParam Map<String, Object> params) {
        int sum = orderService.queryTotal(params);

        return R.ok().put("sum", sum);
    }

    /**
     * 确定收货
     *
     * @param id
     * @return
     */
    @RequestMapping("/confirm")
    @RequiresPermissions("order:confirm")
    public R confirm(@RequestBody Integer id) {
        orderService.confirm(id);

        return R.ok();
    }

    /**
     * 发货
     *
     * @param order
     * @return
     */
    @RequestMapping("/sendGoods")
    @RequiresPermissions("order:sendGoods")
    public R sendGoods(@RequestBody OrderEntity order) {
        orderService.sendGoods(order);

        return R.ok();
    }

    /**
     * 退款
     * @param id
     * @return
     */
    @RequestMapping("/refund")
    public R refund(@RequestBody Integer id) {
        OrderEntity orderEntity = orderService.queryObject(id);
        if (null == orderEntity) {
            return R.error("无效订单");
        }

        Map<String, Object> paramsMap =new HashMap<String, Object>();
        paramsMap.put("orderId", id);
        List<OrderGoodsEntity> list=  orderGoodsService.queryList(paramsMap);

        for (OrderGoodsEntity orderGoodsEntity : list) {
            GoodsEntity goodsEntity = goodsService.queryObject(orderGoodsEntity.getGoodsId());
            if(!goodsEntity.getIsSecKill().equals(5)){// 非活动商品
                return R.error("订单中包含非活动商品，不能退款");
            }
        }

        if (orderEntity.getPayStatus() != 2) {
            return R.error("订单未付款，不能退款");
        }
        if (orderEntity.getOrderStatus() == 4) {
            return R.error("订单已完成，不能退款");
        }
        if (orderEntity.getOrderStatus() == 5) {
            return R.error("订单已退款，不能重复退款");
        }

        MlsUserEntity2 fxUser = mlsUserService.queryByUserId(new Long(orderEntity.getUserId()));

        UserEntity user = userService.queryObject(orderEntity.getUserId());

        if(StringUtils.isNotEmpty(orderEntity.getPayId())){ // 微信支付
            HttpHeaders headers = new HttpHeaders();
            HttpMethod method = HttpMethod.POST;
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add("token", user.getWeixinOpenid());
            //将请求头部和参数合成一个请求
            MultiValueMap<String, Integer> params = new LinkedMultiValueMap<>();
            params.add("orderId", id);
            HttpEntity<MultiValueMap<String, Integer>> requestEntity = new HttpEntity<>(params, headers);

            log.info("调用api退款接口请求, request:{}, url:{}", null, remoteConfig.getFullRefundUrl());
            ResponseEntity<Map> resp = restTemplate.exchange(remoteConfig.getFullRefundUrl(), HttpMethod.POST, requestEntity, Map.class);
            log.info("调用api退款接口应答, resp:{}", resp.getBody());

            if(resp.getBody() != null && resp.getBody().get("errno") != null
                    &&(Integer)resp.getBody().get("errno") == 0){
                // 记录流水
                UserRecordEntity userRecordEntity = new UserRecordEntity();
                userRecordEntity.setMlsUserId(fxUser.getMlsUserId());
                userRecordEntity.setTypes(1);// 后台调整
                userRecordEntity.setTypesStr("后台调整");
                userRecordEntity.setPrice(orderEntity.getActualPrice().intValue());
                userRecordEntity.setRemarks("微信支付退款："+orderEntity.getActualPrice()+",订单号："+orderEntity.getOrderSn());
                userRecordEntity.setAmount(new BigDecimal(fxUser.getAllProfit()));// 余额不变
                userRecordEntity.setDirection(-1);
                userRecordDao.save(userRecordEntity);
            }else{
                return R.error("退款失败，请联系管理员");
            }
        }else{ // 余额支付
            // 记录流水
            UserRecordEntity userRecordEntity = new UserRecordEntity();
            userRecordEntity.setMlsUserId(fxUser.getMlsUserId());
            userRecordEntity.setTypes(1);// 后台调整
            userRecordEntity.setTypesStr("后台调整");
            userRecordEntity.setPrice(orderEntity.getActualPrice().intValue());
            userRecordEntity.setRemarks("余额支付退款："+orderEntity.getActualPrice()+",订单号："+orderEntity.getOrderSn());
            userRecordEntity.setAmount(new BigDecimal(fxUser.getAllProfit() + orderEntity.getActualPrice().intValue()));
            userRecordEntity.setDirection(1);
            userRecordDao.save(userRecordEntity);

            // 增加用户余额
            MlsUserEntity2  mlsUserVo = new MlsUserEntity2();
            //更新余额，退实际支付的
            mlsUserVo.setGetProfit(orderEntity.getActualPrice().intValue());
            mlsUserVo.setMlsUserId(fxUser.getMlsUserId());
            // 退款时，还是退回到可用余额
            mlsUserVo.setGetActivityProfit(0);
            mlsUserService.updateMoney(mlsUserVo);

            //修改订单状态
            orderEntity.setOrderStatus(5);
            orderService.update(orderEntity);
        }

        return R.ok();
    }
}
